<template>
  <div>

    <el-upload
      :action="uploadUrl"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      style="display: none"
      ref="upload"
      v-if="this.type == 'url'"
    >
    </el-upload>

    <!-- WangEditor 容器 -->
    <div class="editor" ref="editor" :style="styles"></div>
  </div>
</template>

<script>
import WangEditor from "wangeditor";
import { getToken } from "@/utils/auth";

export default {
  name: "WangEditor",
  props: {
    value: {
      type: String,
      default: "",
    },
    height: {
      type: Number,
      default: null,
    },
    minHeight: {
      type: Number,
      default: null,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    fileSize: {
      type: Number,
      default: 5,
    },
    type: {
      type: String,
      default: "url",
    }
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      editor: null,
      currentValue: this.value,
    };
  },
  computed: {
    styles() {
      let style = {};
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      return style;
    },
  },
  watch: {
    value(newVal) {
      if (newVal !== this.currentValue) {
        this.currentValue = newVal;
        if (this.editor) {
          this.editor.txt.html(this.currentValue);
        }
      }
    }
  },
  mounted() {
    this.initEditor();
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
    }
  },
  methods: {
    initEditor() {
      this.editor = new WangEditor(this.$refs.editor);
      this.editor.config.readOnly = this.readOnly;
      this.editor.config.onchange = (newHtml) => {
        this.currentValue = newHtml;
        this.$emit("input", newHtml); // 触发数据更新
      };

      // 图片和视频上传配置
      if (this.type === 'url') {
        // console.log(this.type)
        this.editor.config.uploadImgShowBase64 = false;
        this.editor.config.uploadImgServer = this.uploadUrl;
        this.editor.config.uploadImgHeaders = this.headers;
        this.editor.config.uploadImgMaxSize = this.fileSize * 1024 * 1024; // 文件大小限制
        this.editor.config.uploadImgAccept = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml']; // 图片类型限制
        this.editor.config.uploadVideoAccept = ['video/mp4', 'video/webm', 'video/ogg']; // 视频类型限制

        this.editor.config.uploadImgHooks = {
          customInsert: (insertImgFn, result) => {
            console.log("customInsert", result)
            if (result.code === 200) {
              console.log("插入托盘")
              const imgUrl = process.env.VUE_APP_BASE_API + result.fileName;
              insertImgFn(imgUrl); // 插入图片
            } else {
              this.$message.error("图片上传失败");
            }
          },
        };

        this.editor.config.uploadVideoHooks = {
          customInsert: (insertVideoFn, result) => {
            if (result.code === 200) {
              const videoUrl = process.env.VUE_APP_BASE_API + result.fileName;
              insertVideoFn(videoUrl); // 插入视频
            } else {
              this.$message.error("视频上传失败");
            }
          },
        };
      }

      this.editor.create();
      this.editor.txt.html(this.value); // 初始化时填充内容
    },
    handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/svg+xml"];
      const isImage = type.includes(file.type);
      if (!isImage) {
        this.$message.error("只能上传图片格式!");
        return false;  // 如果不是图片类型则返回 false，阻止上传
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },



    handleUploadSuccess(res) {
      // 图片或视频上传成功后的回调
      if (res.code === 200) {
        const fileUrl = process.env.VUE_APP_BASE_API + res.fileName;
        const fileType = res.fileType; // 后端返回文件类型 (image/video)

        if (fileType === 'image') {
          this.editor.cmd.do('insertHTML', `<img src="${fileUrl}" />`);
        } else if (fileType === 'video') {
          this.editor.cmd.do('insertHTML', `<video controls src="${fileUrl}" />`);
        }
      } else {
        this.$message.error("上传失败");
      }
    },
    handleUploadError() {
      this.$message.error("上传失败");
    },
  },
};
</script>

<style>
.editor {
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.w-e-text-container {
  height: 100% !important;
}
</style>
